<template>
  <!-- top -->
  <NEl class="top-com pt-3 pb-3 pl-5 pr-5">
    <!-- tabs -->
    <div class="ml-2">
      <NTabs @update-value="changeOrder" size="large">
        <NTabPane name="1" tab="最新"></NTabPane>
        <NTabPane name="2" tab="高赞"></NTabPane>
        <NTabPane name="3" tab="热评"></NTabPane>
        <NTabPane name="4" tab="热贴"></NTabPane>
      </NTabs>
    </div>

    <!-- search -->
    <div>
      <NSpace>
        <NInput v-model:value="queryInfo.info" placeholder="搜索标题或内容"></NInput>
        <NButton type="primary" @click="search" :loading="searchLoading">搜索</NButton>
      </NSpace>
    </div>

    <!-- user -->
    <div class="top-d-box" v-if="islogin">
      <!-- userinfo -->
      <div>
        <NButton text size="large" @click="showPublish">我要发贴</NButton>
      </div>

      <div>
        <NButton text size="large">个人首页</NButton>
      </div>

      <div>
        <WuUserInfo></WuUserInfo>
      </div>
    </div>

    <!-- user: 未登录状态 -->
    <div class="top-d-box" v-else>
      <div>
        <NPopover>
          <template #trigger>
            <NButton disabled text size="large">我要发贴</NButton>
          </template>
          <span>请先登录</span>
        </NPopover>
      </div>

      <div>
        <NPopover>
          <template #trigger>
            <NButton disabled text size="large">个人中心</NButton>
          </template>
          <span>请先登录</span>
        </NPopover>
      </div>

      <div>
        <WuUserInfo></WuUserInfo>
      </div>
    </div>
  </NEl>

  <!-- body -->
  <div>
    <!-- 骨架屏 -->
    <div v-if="loading && firstLoad">
      <div v-for="i in 20" :key="i" class="skeleton-box">
        <NCard>
          <div class="message-info">
            <div>
              <NSkeleton height="40px" :sharp="false" circle></NSkeleton>
            </div>
            <div>
              <NSkeleton width="40px" height="1rem" :sharp="false" text></NSkeleton>
              <NSkeleton width="60px" height="0.8rem" :sharp="false" text></NSkeleton>
              <NSkeleton width="300px" height="1.5rem" :sharp="false" text></NSkeleton>
              <div>
                <div><NSkeleton width="60px" height="0.8rem" :sharp="false" text></NSkeleton></div>
                <div><NSkeleton width="60px" height="0.8rem" :sharp="false" text></NSkeleton></div>
                <div><NSkeleton width="60px" height="0.8rem" :sharp="false" text></NSkeleton></div>
              </div>
            </div>
          </div>
        </NCard>
      </div>
    </div>

    <!-- 数据卡片 -->
    <div v-else>
      <div v-for="d in list" :key="d.mid" class="message-box">
        <NCard>
          <div class="message-info">
            <!-- right -->
            <div>
              <NAvatar size="large" round :src="Api.userlogo(d.user.user.id)"></NAvatar>
            </div>
            <!-- left -->
            <div>
              <div>{{ d.user.info.nickname || d.user.user.username }}</div>
              <div>{{ Tools.formatDate(d.lastupdate, 'yyyy-MM-dd') }}</div>
              <div @click="toDetail(d.mid)">{{ d.title }}</div>
              <div>
                <div>{{ d.hits }}人看过</div>
                <div>{{ d.praise }}人赞过</div>
                <div>{{ d.reply }}人参与</div>
                <div v-if="d.exInfo.praised" class="like-info">赞过</div>
                <div v-if="d.exInfo.mine" @click="delMessage(d)" class="del-info">删帖</div>
              </div>
            </div>
          </div>
        </NCard>
      </div>
    </div>
  </div>

  <div>
    <NModal v-model:show="pvisible" title="发布帖子" preset="dialog">
      <div>
        <NInput v-model:value="addMessageInfo.title" placeholder="请输入一个真诚的标题"></NInput>
      </div>
      <div class="mt-5">
        <NInput
          v-model:value="addMessageInfo.info"
          placeholder="请输入一些有内容的内容"
          rows="8"
          type="textarea"
          clearable
        ></NInput>
      </div>

      <template #action>
        <NButton type="primary" @click="addMessage" :loading="loading">发布</NButton>
      </template>
    </NModal>
  </div>

  <!-- 加载中 -->
  <div class="tc p-4" v-if="loading">
    <NSpin>
      <template #description> 莫慌莫慌，马上出来 </template>
    </NSpin>
  </div>
  <!-- 无数据 -->
  <div class="p-4 tc" v-if="page.pageNumber >= page.pageCount && !loading">我是有底线的</div>

  <NBackTop></NBackTop>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import WuUserInfo from '@/components/WuUserInfo.vue'
import type { TbMessage } from '@/types/Message'
import type { BaseDataResult, BaseResult, PageBean, PageVO } from '@/types/BaseResult'
import { Api } from '@/types/Api'
import {
  NAvatar,
  NBackTop,
  NButton,
  NCard,
  NEl,
  NInput,
  NModal,
  NPopover,
  NSkeleton,
  NSpace,
  NSpin,
  NTabPane,
  NTabs,
  useMessage,
  useDialog,
} from 'naive-ui'
const dialog = useDialog()
import { Tools } from '@/types/Tools'
const message = useMessage()
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/userStore'
import router from '@/router'
const { islogin } = storeToRefs(useUserStore())

const loading = ref(false)
const firstLoad = ref(true)

//#region 查询
const list = ref([] as Array<TbMessage>)
const queryInfo = ref({ order: 1, info: '' })
const page = ref({ pageNumber: 1, pageSize: 20 } as PageBean)

const query = () => {
  loading.value = true
  Api.get(
    `/message/${page.value.pageSize}/${page.value.pageNumber}/${queryInfo.value.order}`,
    { info: queryInfo.value.info },
    (data: BaseDataResult<PageVO<TbMessage>>) => {
      loading.value = false
      searchLoading.value = false
      if (data.success) {
        list.value = list.value.concat(data.data.list)
        page.value = data.data.pageBean
        firstLoad.value = false
        return
      }
      message.error(data.message)
    },
  )
}

// 无限滚动
const scroll = () => {
  // console.log('滚动了')
  if (loading.value) {
    return
  }
  // console.log('是否到达底部:', isScrollToBottom())
  if (isScrollToBottom()) {
    loadmore()
  }
}

const loadmore = () => {
  page.value.pageNumber++
  if (page.value.pageNumber > page.value.pageCount) {
    return
  }
  query()
}

const isScrollToBottom = () => {
  const scrollTop = document.documentElement.scrollTop || window.scrollY
  const sh = document.documentElement.scrollHeight
  const ch = document.documentElement.clientHeight
  return scrollTop + ch >= sh - 100
}

onMounted(() => {
  requery()
  window.addEventListener('scroll', scroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', scroll)
})

// 重查
const requery = () => {
  firstLoad.value = true
  page.value.pageNumber = 1
  queryInfo.value.info = ''
  list.value = []
  query()
}

// tabs
const changeOrder = (order: number) => {
  queryInfo.value.order = order
  requery()
}

// search
const searchLoading = ref(false)

const search = () => {
  firstLoad.value = true
  searchLoading.value = true
  page.value.pageNumber = 1
  list.value = []
  query()
}

//#endregion

// 详情页
const toDetail = (mid: number) => {
  window.open(router.resolve(`/message/${mid}`).href)
  // router.push(`/message/${mid}`)
}

//#region 发布帖子
const pvisible = ref(false)
const pLoading = ref(false)
const addMessageInfo = ref({ title: '', info: '' } as TbMessage)
const showPublish = () => {
  addMessageInfo.value.title = ''
  addMessageInfo.value.info = ''
  pvisible.value = true
}

const addMessage = () => {
  pLoading.value = true
  Api.post('/message', addMessageInfo.value, (data: BaseResult) => {
    pLoading.value = false
    if (data.success) {
      message.success('发布成功')
      pvisible.value = false
      requery()
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 删除帖子
const delMessage = (mid: TbMessage) => {
  dialog.error({
    title: '警告',
    content: `确定要删除吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      Api.delete(`/message/${mid.mid}`, {}, (data: BaseResult) => {
        if (data.success) {
          message.success('删除成功')
          requery()
          return
        }
        message.error(data.message)
      })
    },
  })
}
//#endregion
</script>

<style scoped lang="scss">
.top-d-box {
  display: flex;
  align-items: center;
  > div {
    margin: 0 10px;
  }
}

.message-box {
  width: 61.8vw;
  margin: 1rem auto;
  .message-info {
    display: flex;
    // right
    > div:last-of-type {
      margin-left: 1rem;
      // 发布时间
      > div:nth-of-type(2) {
        font-size: 0.8rem;
        color: #999;
      }
      // 标题
      > div:nth-of-type(3) {
        font-size: 1.5rem;
        margin: 0.2rem 0;
        &:hover {
          cursor: pointer;
          color: #7fe7c4;
          transition: color 0.5s;
        }
        &:active {
          color: #5acea7;
        }
      }
      // 阅读数，点赞数，评论数
      > div:nth-of-type(4) {
        display: flex;
        gap: 1rem;
        font-size: 0.8rem;
        color: #999;
        .like-info {
          background-color: #333;
          border-radius: 3px;
          padding: 0.001rem 0.3rem;
        }
        .del-info {
          background-color: #333;
          border-radius: 3px;
          padding: 0.001rem 0.3rem;
          cursor: pointer;
        }
      }
    }
  }
}

.skeleton-box {
  width: 61.8vw;
  margin: 1rem auto;
  .message-info {
    display: flex;
    margin: 0.2rem 0;
    > div:last-of-type {
      margin-left: 1rem;
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      > div:last-of-type {
        display: flex;
        gap: 1rem;
      }
    }
  }
}
</style>
